package vn.vfriends.vbox.facade;

import java.util.List;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import javax.validation.constraints.NotNull;
import vn.vfriends.vbox.model.Provider;
import vn.vfriends.vbox.model.User;

/**
 *
 * @author tuancn
 */
@Stateless
public class UserFacade extends AbstractFacade<User> {
    
    @PersistenceContext(unitName = "vBoxPU")
    private EntityManager em;

    @Override
    protected EntityManager getEntityManager() {
        return em;
    }
    
    public UserFacade() {
        super(User.class);
    }

    public User createUser(@NotNull User user) {
        super.create(user);
        return user;
    }

    public User editUser(@NotNull User user) {
        super.edit(user);
        return user;
    }

    public void remove(Integer id) {
        super.remove(super.find(id));
    }

    public User find(Integer id) {
        return super.find(id);
    }
    
    public User find(@NotNull String username, @NotNull String provider) {
        Query query = em.createNamedQuery("User.find", User.class);
        query.setParameter("username", username);
        query.setParameter("provider", Provider.valueOf(provider));
        List<User> userList = query.getResultList();
        if(userList != null && !userList.isEmpty())
            return userList.get(0);
        else
            return null;
    }

    public User findByUsername(@NotNull String username) {
        Query query = em.createNamedQuery("User.findByUsername", User.class);
        query.setParameter("username", username);
        List<User> userList = query.getResultList();
        if(userList != null && !userList.isEmpty())
            return userList.get(0);
        else
            return null;
    }
    
    @Override
    public List<User> findAll() {
        return super.findAll();
    }

    public List<User> findRange(@NotNull Integer from, @NotNull Integer to) {
        return super.findRange(new int[]{from, to});
    }

    @Override
    public int count() {
        return super.count();
    }
}
